* Create past AE treatment for each cardio patient for merge in random checks

foreach year in 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 {

use "$savedata/amipats_ids0517_v2.dta", clear
	
merge 1:m extract using "$eddata/data_ae`year'"
drop if _m==2

gen visit_ae = 0
replace visit_ae = 1 if _merge==3
gen cardio_ae = 0
replace cardio_ae = 1 if d1==20

replace d_amb = 0 if d_amb==.

drop _merge

collapse (sum) visit_ae cardio_ae d_amb, by(extract)

gen any_visit_ae`year' = 0
replace any_visit_ae`year' = 1 if visit_ae>0

gen any_cardio_ae`year' = 0
replace any_cardio_ae`year' = 1 if cardio_ae>0

gen any_amb`year' = 0
replace any_amb`year' = 1 if d_amb>0

rename visit_ae num_visit_ae`year'
rename cardio_ae num_cardio_ae`year'
rename d_amb num_amb_ae`year'

save "$savedata/ae`year'.dta", replace

	}
	
use "$savedata/ae2007.dta", clear

foreach year in 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 {
	merge 1:1 extract using "$savedata/ae`year'.dta"
	drop _merge
}

save "$savedata/pastae0717.dta", replace

